package com.qm.console.component.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by fangzhipeng on 2017/10/23
 */
public class GetPropertiesUtils {

    private final static String CLASSPATH = "classpath:";
    private final static String FILE_SUBFIX = ".properties";
    private static Map<String, Map<String, String>> cache = new HashMap<>();


    public static String getProperty(String fileName, String property) {
        fileName = CLASSPATH + fileName + FILE_SUBFIX;
        if (cache.get(fileName) != null) {
            return cache.get(fileName).get(property);
        } else {
            synchronized (GetPropertiesUtils.class) {
                Map<String, String> propertiesMap = new HashMap<>();
                cache.put(fileName, propertiesMap);
                InputStream inputStream = null;
                try {
                    inputStream = ResourceUtil.getResouce(fileName).getInputStream();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Properties properties = new Properties();
                try {
                    properties.load(inputStream);
                    Enumeration propertyNames = properties.propertyNames();
                    for (;propertyNames.hasMoreElements();) {
                        String propertyName = (String) propertyNames.nextElement();
                        cache.get(fileName).put(propertyName, (String) properties.get(propertyName));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return cache.get(fileName).get(property);
    }

}
